import { useRef } from 'react'
// 引入 connect 用于链接 UI 组件和 redux
import { connect } from 'react-redux'
// 引入 action
import { createIncrementAction, createDecrementAction, createAsyncInreacementAction } from '../redux/actions/counter_action'


const CompletedReduxCounterComponent = (props) => {

    const selectRef = useRef()

    // 获取 react-redux 中 connect map 过来的 store 值，及 dispatch 函数
    const {
        count,
        increment,
        decrement,
        asyncIncrement,
        personInfo
    } = props

    const onIncreacementBtnClicked = () => {
        const { value: step } = selectRef.current
        increment(step)

    }
    const onSubtractionBtnClicked = () => {
        const { value: step } = selectRef.current
        decrement(step)

    }
    const onIncreaceIfEvenBtnClicked = () => {
        const { value: step } = selectRef.current
        if (!(count % 2)) increment(step)
    }
    const onAsyncIncreacementBtnClicked = () => {
        const { value: step } = selectRef.current
        asyncIncrement(step, 500)
    }

    return (
        <>
            <h3>This is Counter component</h3>
            <h4>当前和为：{count},当前人数为：{personInfo?.length}</h4>
            <select ref={selectRef}>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
            </select>&nbsp;
            <button onClick={onIncreacementBtnClicked}>加！</button>&nbsp;
            <button onClick={onSubtractionBtnClicked}>减！</button>&nbsp;
            <button onClick={onIncreaceIfEvenBtnClicked}>偶数再加！</button>&nbsp;
            <button onClick={onAsyncIncreacementBtnClicked}>等会儿加！</button>
        </>
    )
}

export default connect(
    state => ({
        count: state.counter,
        personInfo: state.person
    }),
    {
        increment: createIncrementAction,
        decrement: createDecrementAction,
        asyncIncrement: createAsyncInreacementAction
    })
    (
        CompletedReduxCounterComponent
    )